<template>
  <div class="about-master-container">
    <base-breadcrumb :breadcrumb="!isAudit">
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="formData"
              :rules="rules"
            >
              <a-row>
                <a-col span="8">
                  <!-- 编辑时才显示-->
                  <a-form-model-item
                    label="剩余物资处置申请编码"
                    prop="disposalApplyCode"
                  >
                    <a-input-search
                      v-model="formData.disposalApplyCode"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @search="openDisposal"
                      @click="openDisposal"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="剩余物资结算单编码">
                    <BaseInput
                      v-model="formData.code"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="项目名称">
                    <a-select
                      v-model="formData.projectId"
                      disabled
                    >
                      <a-select-option
                        v-for="item in projectPast"
                        :key="item.code"
                        :value="item.code"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="编号"
                    prop="number"
                  >
                    <BaseInput
                      v-model="formData.number"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="处理日期"
                    prop="settleDate"
                  >
                    <a-date-picker
                      v-model="formData.settleDate"
                      value-format="YYYY-MM-DD"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="计量方式"
                    prop="measurementMethodId"
                  >
                    <a-select
                      v-model="formData.measurementMethodId"
                      :disabled="state === 3"
                    >
                      <a-select-option
                        v-for="item in wayArr"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="收购方"
                    prop="acquirerName"
                  >
                    <a-input-search
                      v-model="formData.acquirerName"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @search="openAcquisition"
                      @click="openAcquisition"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="分包商名称"
                    prop="subContractorName"
                  >
                    <a-input-search
                      v-model="formData.subContractorName"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @search="openSubcontract"
                      @click="openSubcontract"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput
                      v-model="formData.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput
                      v-model="formData.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="temporaryStorage()"
              >
                保存草稿
              </a-button>
              <a-button
                type="primary"
                @click="temporaryStorage(true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="结算明细">
          <a-card
            v-if="activeKey[1]"
            slot="description"
            :bordered="false"
          >
            <detail
              :id="row ? row.id : null"
              ref="detail"
              :state="state"
              :disposal-apply-id="formData.disposalApplyId"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="state !== 3"
              :list-url="fileList"
              :business-id="row.id"
              business-code="MM01"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div
        v-if="!isAudit"
        class="pub-header-btn page-btn-right-top"
      >
        <template v-if="state !== 3">
          <a-button
            type="primary"
            :loading="loading"
            @click="submit"
          >
            提交
          </a-button>
          <a-button
            type="primary"
            :loading="loading"
            @click="temporaryStorage"
          >
            保存
          </a-button>
        </template>
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
      <supplier-list
        ref="supplierAcquisition"
        @createList="getAcquisition"
      />
      <subcontractor
        ref="subcontract"
        @getSubcontractor="getSubcontract"
      />
      <disposal
        ref="disposal"
        :other-data="otherData"
        @getDisposal="getDisposal"
      />
       <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
  </div>
</template>

<script>
import { themeChoose } from '@/mixin/mixin'
import detail from '../components/detail/detail'
import disposal from '../components/disposal/disposal'
import subcontractor from '../components/subcontractor/subcontractor'
import { settlementAdd, settlementEdit, audit, addFile, fileList, fileDel, getRestMaterialBaseInfo} from '@/api/material/remaining/settlement'
import { selectOption } from '@/api/material/goods/goods'

export default {
	name:'a'+Date.now(),
    mixins: [themeChoose],
    components: {
        detail,
        disposal,
        subcontractor
    },

    props: {
        isAudit: { // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.state = 3
                }
            }
        },
        stepVal(newVal, oldVal) {
            this.$set(this.activeKey, newVal, true)
        }
    },
    data() {
        return {
            activeKey: [true, false, false, false, false, false, false],
            loading: false,
            state: Number(this.$route.query.state),
            isSubmit: false,
            otherData: { disposalMethodId: '623332175915388928' },
            // row: this.$route.query.row,
            row: {},
            formData: {
                createTime: this.getNowTime(),
                creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
                disposalApplyCode: '',
                code: '',
                projectId: null,
                projectCode: '',
                number: '',
                settleDate: null,
                measurementMethodId: null,
                acquirerId: null,
                subContractorId: null,
                disposalApplyId: null,
                acquirerName: '',
                subContractorName: ''
            },
            isNext: false,
            stepVal: 0,
            addFile: addFile(),
            fileDel: fileDel(),
            fileList: fileList(),
            wayArr: [],
            rules: {
                disposalApplyCode: { required: true, message: '剩余物资处置申请编码不能为空', trigger: 'change' },
                number: { required: true, message: '编号不能为空', trigger: 'blur' },
                settleDate: { required: true, message: '处理日期不能为空', trigger: 'change' },
                measurementMethodId: { required: true, message: '计量方式不能为空', trigger: 'blur' },
                acquirerName: { required: true, message: '收购方不能为空', trigger: 'change' },
                subContractorName: { required: true, message: '分包商名称不能为空', trigger: 'change' }
            },
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
   async mounted() {
        this.getWay()
        if (this.state !== 1) {
            this.getRestMaterialBaseInfoReq(this.$route.query.id)
            this.isSubmit = true
        }
        //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('mm_surplus_settle')
    },
    methods: {
        async getRestMaterialBaseInfoReq(id) {
            if(!id) return
            try {
                this.loading = true
                const res = await getRestMaterialBaseInfo({id})
                this.loading = false
                this.row = res.data || {}
                this.getEditInfo()
            } catch(e) {
                console.error(e)
                this.loading = false
            }
        },
        getWay: function() {
            let _this = this
            selectOption({
                type: 29
            }).then(res => {
                if (res.code === 200) {
                    _this.wayArr = res.data
                    _this.formData.measurementMethodId = res.data[0].id
                }
            })
        },
        openDisposal: function() {
            this.$refs.disposal.open()
        },
        getDisposal: function(row) {
            this.formData.projectId = row.projectId
            this.formData.projectCode = row.projectCode
            this.formData.disposalApplyCode = row.code
            this.formData.disposalApplyId = row.id
        },
        openAcquisition: function() {
            this.$refs.supplierAcquisition.open()
        },
        getAcquisition: function(row) {
            this.formData.acquirerId = row.id
            this.formData.acquirerName = row.name
        },
        openSubcontract: function() {
            this.$refs.subcontract.open()
        },
        getSubcontract: function(row) {
            this.formData.subContractorId = row.id
            this.formData.subContractorName = row.name
        },
        stepChange: function(val) {
            if (!this.row && !this.isAudit) {
                if (val) {
                    this.$message.warning('切换步骤前请先填写基本信息')
                    this.stepVal = 0
                }
            } else {
                if (!this.isNext) {
                    this.$set(this.activeKey, val, !this.activeKey[val])
                }
            }
            this.isNext = false
        },
        next: function(val) {
            this.isNext = true
            this.stepVal++
        },
        previous: function() {
            this.isNext = true
            this.stepVal--
            if (this.stepVal < 0) {
                this.stepVal = 0
            }
        },
        // 获取编辑回显数据
        getEditInfo() {
            this.formData.createTime = this.row.createTime
            this.formData.creatorName = this.row.creatorName
            this.formData.disposalApplyCode = this.row.disposalApplyCode
            this.formData.code = this.row.code
            this.formData.projectId = this.row.projectId
            this.formData.projectCode = this.row.projectCode
            this.formData.number = this.row.number
            this.formData.settleDate = this.row.settleDate
            this.formData.measurementMethodId = this.row.measurementMethodId
            this.formData.acquirerId = this.row.acquirerId
            this.formData.subContractorId = this.row.subContractorId
            this.formData.disposalApplyId = this.row.disposalApplyId
            this.formData.acquirerName = this.row.acquirerName
            this.formData.subContractorName = this.row.subContractorName
        },
        submit() {
            // this.save('approve');
            if (this.isSubmit) {
                  this.submitApprovalConfirm(this.isSubmit?this.processConfig:6, async(flag)=>{
                    if(!flag) {
                      this.loading = false
                      return
                    }
                    this.loading = true
                    let res = await audit({ baseId: this.row.id, auditStatus: this.row.auditStatus })
                    this.loading = false
                    if (res.code === this.SUCCESS_CODE) {
                        this.$message.success('提交成功')
                        //提交时，返回id
                        this.businessId = this.row.id;
                        this.setProcessConfig = this.processConfig;
                        // this.$router.push({ path: '/material/remaining/settlement' })
                    }
                })
            } else {
                this.$message.warning('提交之前请先暂存')
            }
        },
        temporaryStorage(isNext) {
            if (this.state === 3) {
                this.next()
                return
            }
            this.$refs.ruleForm.validate(async (valid, object) => {
                if (valid) {
                    this.loading = true
                    if (this.state === 2 || this.row?.id) {

                        this.formData.id = this.row.id
                        let res = await settlementEdit(this.formData)
                        this.loading = false
                        if (res.code === 200) {
                            this.$message.success('暂存成功')
                            this.isSubmit = true
                            if (isNext) {
                                this.next()
                            }
                        }else{
                        }
                    } else {
                        settlementAdd(this.formData).then((res)=>{
                           this.loading = false
                           if (res?.code === 200) {
                            this.row = res.data
                            this.$message.success('暂存成功')
                            this.isSubmit = true
                            this.getEditInfo()
                            if (isNext) {
                                this.next()
                            }
                        }else{
                        }

                        }).catch((err)=>{
                           this.loading = false
                        })


                    }
                } else {
                  this.$message.warning("请填写完所有必填项信息")
                    return false
                }
            })
        }
    }
}
</script>
